﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ElementumForever.Interfaces;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ElementumForever
{
   public class EntityList : IEnumerable 
    {
       private readonly List<IEntity> _entities = new List<IEntity>(); 
        static readonly EntityComparer Comparer = new EntityComparer();
             
        public void Sort(){
        _entities.Sort(Comparer);
        }

        class EntityComparer : IComparer<IEntity> {//decress

            public int Compare(IEntity x, IEntity y)
            {
                if (x.LayerDepth > y.LayerDepth)
                    return 1;
                if (x.LayerDepth < y.LayerDepth)
                    return -1;
                return 0;
            }
        }

        public void Clear() {
            _entities.Clear();
        }

        public void Add(BaseEntity entity)
        {
            _entities.Add(entity);
        }

        public void Remove(BaseEntity entity)
        {
            _entities.Remove(entity);
        }

        public void OnDraw(GameTime gameTime, SpriteBatch spriteBatch) {
            for (int i = _entities.Count - 1; i >= 0; i--) {
                _entities[i].OnDraw(gameTime, spriteBatch);
            }
                //foreach (IEntity i in _entities)
                //{
                //    i.OnDraw(gameTime, spriteBatch);
                //}
        }

        public void OnUpdate(GameTime gameTime)
        {
            foreach (IEntity i in _entities)
            {
                i.OnUpdate(gameTime);
            }
        }

        public IEnumerator GetEnumerator()
        {
            return _entities.GetEnumerator();
        }

        public IEntity Get(int index)
        {
            return _entities[index];
        }

        public int Count {
            get
            {
                return _entities.Count;
            }
        }
       
    }
}
